package com.lanren.familybookapp.ui.table.view;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gitee.mikephil.charting.animation.Easing;
import com.gitee.mikephil.charting.charts.LineChart;
import com.gitee.mikephil.charting.charts.PieChart;
import com.gitee.mikephil.charting.components.Legend;
import com.gitee.mikephil.charting.components.XAxis;
import com.gitee.mikephil.charting.components.YAxis;
import com.gitee.mikephil.charting.data.Entry;
import com.gitee.mikephil.charting.data.LineData;
import com.gitee.mikephil.charting.data.LineDataSet;
import com.gitee.mikephil.charting.data.PieData;
import com.gitee.mikephil.charting.data.PieDataSet;
import com.gitee.mikephil.charting.data.PieEntry;
import com.gitee.mikephil.charting.formatter.IFillFormatter;
import com.gitee.mikephil.charting.formatter.PercentFormatter;
import com.gitee.mikephil.charting.highlight.Highlight;
import com.gitee.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.gitee.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.gitee.mikephil.charting.listener.OnChartValueSelectedListener;
import com.gitee.mikephil.charting.utils.ColorTemplate;
import com.gitee.mikephil.charting.utils.MPPointF;
import com.lanren.common.utils.DateUtils;
import com.lanren.common.utils.LogUtils;
import com.lanren.common.utils.StringUtils;
import com.lanren.common.utils.Utils;
import com.lanren.common.widget.SwitchMultiButton;
import com.lanren.common.widget.pickerview.TimePickerDialog;
import com.lanren.common.widget.pickerview.data.Type;
import com.lanren.common.widget.pickerview.listener.OnDateSetListener;
import com.lanren.common.widget.statusbar.ImmersionBar;
import com.lanren.familybookapp.R;
import com.lanren.familybookapp.app.AppUserHelper;
import com.lanren.familybookapp.base.BaseUiLazyFragment;
import com.lanren.familybookapp.ui.table.bean.InOutStatisticsBean;
import com.lanren.familybookapp.ui.table.bean.TotalStaticsBean;
import com.lanren.familybookapp.ui.table.interfaces.ITableModel;
import com.lanren.familybookapp.ui.table.model.TableModel;
import com.lanren.familybookapp.ui.table.presenter.TablePresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * @ClassName TableFragment
 * @Description TODO  图表总结显示
 * @Author chongheng.wang
 * @Date 2019/10/5 16:53
 * @Version 1.0
 */
public class TableFragment extends BaseUiLazyFragment<TablePresenter> implements ITableModel.ITableView {


    @BindView(R.id.book_time_type)
    SwitchMultiButton bookTimeType;
    @BindView(R.id.book_time)
    TextView bookTime;
    @BindView(R.id.book_time_view)
    LinearLayout bookTimeView;
    @BindView(R.id.zong_out_value)
    TextView zongOutValue;
    @BindView(R.id.zong_in_value)
    TextView zongInValue;
    @BindView(R.id.average_value)
    TextView averageValue;
    @BindView(R.id.balance_value)
    TextView balanceValue;
    @BindView(R.id.line_chart)
    LineChart lineChart;
    @BindView(R.id.book_in_out_type)
    SwitchMultiButton bookInOutType;
    @BindView(R.id.classify)
    PieChart classify;
    @BindView(R.id.member)
    PieChart member;
    @BindView(R.id.wb_refresh)
    SmartRefreshLayout wbRefresh;
    @BindView(R.id.line_view)
    LinearLayout lineView;

    private TimePickerDialog mDialogYearMonth;
    private Type mBookTimeType = Type.YEAR_MONTH;
    private int bookType = 1;

    public static TableFragment newInstance() {
        return new TableFragment();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_table;
    }

    @Override
    public TablePresenter createPresenter() {
        return new TablePresenter(new TableModel());
    }

    @Override
    protected void setStatusBar() {
        mImmersionBar = ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
    }

    @Override
    protected void initFragment() {
        initView();
        initData();
        initEvent();
    }

    private void initView() {
        bookTimeType.setText("月", "年");
        bookInOutType.setText("支出", "收入");
        mDialogYearMonth = setTimePickerDialog(Type.YEAR_MONTH);
        bookTime.setText(DateUtils.longToFormat(DateUtils.getNowTime(), "yyyy年MM月"));

        initLineChart();
        initPieClassify();
        initPieMember();
        wbRefresh.setEnableLoadMore(false);
    }

    private void initData() {
        getTotal();
    }


    private void initEvent() {
        bookTimeType.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                LogUtils.d("bookTimeType====" + tabText + position);
                if (position == 1) {
                    mBookTimeType = Type.YEAR;
                    mDialogYearMonth = setTimePickerDialog(Type.YEAR);
                    bookTime.setText(DateUtils.longToFormat(DateUtils.getNowTime(), "yyyy年"));
                } else {
                    mBookTimeType = Type.YEAR_MONTH;
                    mDialogYearMonth = setTimePickerDialog(Type.YEAR_MONTH);
                    bookTime.setText(DateUtils.longToFormat(DateUtils.getNowTime(), "yyyy年MM月"));
                }
                getTotal();
            }
        });

        bookInOutType.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                LogUtils.d("bookInOutType====" + tabText + position);
                bookType = position + 1;
                if (AppUserHelper.getInstance().getUser().getUserUseBook() != 0) {
                    mPresenter.getStatistics(AppUserHelper.getInstance().getUser().getUserUseBook(),
                            getBookTime(), bookType);
                }
            }
        });

        bookTimeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick(v)) {
                    if (mDialogYearMonth != null) {
                        mDialogYearMonth.show(getActivity());
                    }
                }
            }
        });

        wbRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (AppUserHelper.getInstance().getUser().getUserUseBook() == 0) {
                    wbRefresh.finishRefresh();
                } else {
                    getTotal();
                }
            }
        });
    }

    private void getTotal() {
        if (AppUserHelper.getInstance().getUser().getUserUseBook() == 0) {
            showEmpty();
            zongOutValue.setText("--");
            zongInValue.setText("--");
            averageValue.setText("--");
            balanceValue.setText("--");
        } else {
            mPresenter.getTotal(AppUserHelper.getInstance().getUser().getUserUseBook(), getBookTime());

        }
    }


    private String getBookTime() {
        String time = null;
        if (mBookTimeType == Type.YEAR) {
            time = DateUtils.stringToFormat2(bookTime.getText().toString());
        } else if (mBookTimeType == Type.YEAR_MONTH) {
            time = DateUtils.stringToFormat(bookTime.getText().toString());
        }
        return time;
    }

    @Override
    protected void onRestart() {

    }

    @Override
    public void showError(int code, String msg) {
        if (code == 10009) {
            showEmpty();
            lineView.setVisibility(View.GONE);
        } else {
            wbRefresh.finishRefresh();
            super.showError(code, msg);
        }
    }

    @Override
    public void onSuccessTotal(TotalStaticsBean totalStaticsBean) {
        showComplete();
        lineView.setVisibility(View.VISIBLE);
        wbRefresh.finishRefresh();
        zongOutValue.setText(StringUtils.doubleIsNullByPstr(totalStaticsBean.getTotalOut(), "--"));
        zongInValue.setText(StringUtils.doubleIsNullByPstr(totalStaticsBean.getTotalIn(), "--"));
        averageValue.setText(StringUtils.doubleIsNullByPstr(totalStaticsBean.getAverage(), "--"));
        balanceValue.setText(StringUtils.doubleIsNullByPstr(totalStaticsBean.getBalance(), "--"));

        List<Double> staticsList = totalStaticsBean.getOutInMoneyBean().getOutMoney();
        List<Double> totalList = totalStaticsBean.getOutInMoneyBean().getInMoney();
        setLineChartData(staticsList, totalList);

        mPresenter.getStatistics(AppUserHelper.getInstance().getUser().getUserUseBook(),
                getBookTime(), bookType);
    }

    @Override
    public void onSuccessStatics(InOutStatisticsBean inOutStatisticsBean) {
        List<InOutStatisticsBean.ClassifyMoneyBean> classifyMoneyBean = inOutStatisticsBean.getClassifyMoneyBean();
        List<InOutStatisticsBean.MemberMoneyBean> memberMoneyBean = inOutStatisticsBean.getMemberMoneyBean();

        setClassifyData(classifyMoneyBean);
        setMemberData(memberMoneyBean);

    }

    OnDateSetListener onDateSetListener = new OnDateSetListener() {
        @Override
        public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
            if (mBookTimeType == Type.YEAR) {
                bookTime.setText(DateUtils.longToFormat(millseconds, "yyyy年"));
            } else {
                bookTime.setText(DateUtils.longToFormat(millseconds, "yyyy年MM月"));
            }
            getTotal();
        }
    };

    private TimePickerDialog setTimePickerDialog(Type timeType) {
        TimePickerDialog timePickerDialog = new TimePickerDialog.Builder()
                .setThemeColor(getResources().getColor(R.color.green10))
                .setTitleStringId("选择时间")
                .setMinMillseconds(DateUtils.rollYear(new Date(), -20).getTime())
                .setMaxMillseconds(DateUtils.rollDay(new Date(), 7).getTime())
                .setCurrentMillseconds(DateUtils.getNowTime())
                .setType(timeType)
                .setCallBack(onDateSetListener)
                .setCyclic(false)
                .build();

        return timePickerDialog;
    }


    private void initLineChart() {
        lineChart.setViewPortOffsets(0, 0, 0, 0);
//        lineChart.setBackgroundColor(Color.rgb(104, 241, 175));
        lineChart.setNoDataText("暂无数据");
        lineChart.setNoDataTextColor(Color.parseColor("#999999"));
        // no description text
        lineChart.getDescription().setEnabled(false);

        // enable touch gestures
        lineChart.setTouchEnabled(true);

        // enable scaling and dragging
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(false);

        lineChart.setDrawGridBackground(false);
        lineChart.setMaxHighlightDistance(300);

        //设置是否可以通过双击屏幕放大图表。默认是true
        lineChart.setDoubleTapToZoomEnabled(false);
        //=========================设置图例=========================
        // 像"□ xxx"就是图例
        Legend legend = lineChart.getLegend();
        //设置图例显示在chart那个位置 setPosition建议放弃使用了
        //设置垂直方向上还是下或中
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        //设置水平方向是左边还是右边或中
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        //设置所有图例位置排序方向
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //设置图例的形状 有圆形、正方形、线
        legend.setForm(Legend.LegendForm.SQUARE);
        //是否支持自动换行 目前只支持BelowChartLeft, BelowChartRight, BelowChartCenter
        legend.setWordWrapEnabled(true);
        legend.setEnabled(true);

        XAxis x = lineChart.getXAxis();
        x.setEnabled(false);

        YAxis y = lineChart.getAxisLeft();
        y.setLabelCount(6, false);
        y.setTextColor(getResources().getColor(R.color.colorAccent));
        y.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        y.setDrawGridLines(false);
        y.setAxisLineColor(getResources().getColor(R.color.colorAccent));
        y.setGridColor(getResources().getColor(R.color.colorAccent));

        lineChart.getAxisRight().setEnabled(false);

        lineChart.animateXY(2000, 2000);

        // don't forget to refresh the drawing
        lineChart.invalidate();
    }


    private void setLineChartData(List<Double> staticsList, List<Double> totalList) {

        List<ILineDataSet> dataSets = new ArrayList<>();
        List<List<Entry>> value = new ArrayList<>();

        List<Entry> value1 = new ArrayList<>();
        List<Entry> value2 = new ArrayList<>();

        if (staticsList.size() == 0) {
            value1.add(new Entry(0, 0));
        } else {
            for (int i = 0; i < staticsList.size(); i++) {
                value1.add(new Entry(i, staticsList.get(i).floatValue()));
            }
        }

        if (totalList.size() == 0) {
            value2.add(new Entry(0, 0));
        } else {
            for (int i = 0; i < totalList.size(); i++) {
                value2.add(new Entry(i, totalList.get(i).floatValue()));
            }
        }

        value.add(value1);
        value.add(value2);

        int[] color = new int[]{R.color.colorAccent, R.color.green11};
        String[] label = new String[]{"支出", "收入"};

        LogUtils.d("LineDataSet=" + value.size() + "   " + value1.size() + "   " + value2.size());
        for (int i = 0; i < value.size(); i++) {
            LineDataSet set1 = new LineDataSet(value.get(i), label[i]);
            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            set1.setCubicIntensity(0.2f);
            set1.setDrawFilled(true);
            set1.setDrawCircles(false);
            set1.setLineWidth(1.8f);
            set1.setCircleRadius(4f);
            set1.setCircleColor(getResources().getColor(color[i]));
            set1.setHighLightColor(getResources().getColor(R.color.black60));
            set1.setColor(getResources().getColor(color[i]));
//            set1.setFillColor(getResources().getColor(color[i]));
            set1.setFillAlpha(100);
            set1.setDrawHighlightIndicators(false);
            set1.setFillFormatter(new IFillFormatter() {
                @Override
                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                    return lineChart.getAxisLeft().getAxisMinimum();
                }
            });
            dataSets.add(set1);
        }

        // create a data object with the data sets
        LineData data = new LineData(dataSets);
        data.setValueTextSize(9f);
        data.setDrawValues(false);
        // set data
        lineChart.setData(data);
        lineChart.invalidate();
    }


    private void initPieClassify() {
        classify.setUsePercentValues(true);
        classify.getDescription().setEnabled(false);
        classify.setExtraOffsets(5, 10, 30, 5);
        classify.setNoDataText("暂无数据");
        classify.setNoDataTextColor(Color.parseColor("#999999"));
        classify.setDragDecelerationFrictionCoef(0.95f);

        classify.setCenterText("类别占比");

        classify.setDrawHoleEnabled(true);
        classify.setHoleColor(Color.WHITE);

        classify.setTransparentCircleColor(Color.WHITE);
        classify.setTransparentCircleAlpha(110);

        classify.setHoleRadius(58f);
        classify.setTransparentCircleRadius(61f);

        classify.setDrawCenterText(true);

        classify.setRotationAngle(0);
        // enable rotation of the chart by touch
        classify.setRotationEnabled(true);
        classify.setHighlightPerTapEnabled(true);

        // add a selection listener
        classify.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                if (e == null)
                    return;
                LogUtils.d("VAL SELECTED",
                        "Value: " + e.getY() + ", index: " + h.getX()
                                + ", DataSet index: " + h.getDataSetIndex());
                classify.setUsePercentValues(!classify.isUsePercentValuesEnabled());
                classify.invalidate();
            }

            @Override
            public void onNothingSelected() {
                LogUtils.d("PieChart", "nothing selected");
                classify.setUsePercentValues(!classify.isUsePercentValuesEnabled());
                classify.invalidate();
            }
        });

        classify.animateY(1400, Easing.EaseInOutQuad);
        // chart.spin(2000, 0, 360);

        Legend l = classify.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(0f);

        // entry label styling
        classify.setEntryLabelColor(Color.WHITE);
        classify.setEntryLabelTextSize(12f);
    }

    private void initPieMember() {
        member.setUsePercentValues(true);
        member.getDescription().setEnabled(false);
        member.setExtraOffsets(5, 10, 30, 5);
        member.setNoDataText("暂无数据");
        member.setNoDataTextColor(Color.parseColor("#999999"));
        member.setDragDecelerationFrictionCoef(0.95f);

        member.setCenterText("成员占比");

        member.setDrawHoleEnabled(true);
        member.setHoleColor(Color.WHITE);

        member.setTransparentCircleColor(Color.WHITE);
        member.setTransparentCircleAlpha(110);

        member.setHoleRadius(58f);
        member.setTransparentCircleRadius(61f);

        member.setDrawCenterText(true);

        member.setRotationAngle(0);
        // enable rotation of the chart by touch
        member.setRotationEnabled(true);
        member.setHighlightPerTapEnabled(true);

        // chart.setUnit(" €");
        // chart.setDrawUnitsInChart(true);

        // add a selection listener
        member.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                if (e == null) {
                    return;
                }
                member.setUsePercentValues(!member.isUsePercentValuesEnabled());
                member.invalidate();

                LogUtils.d("VAL SELECTED",
                        "Value: " + e.getY() + ", index: " + h.getX()
                                + ", DataSet index: " + h.getDataSetIndex());
            }

            @Override
            public void onNothingSelected() {
                member.setUsePercentValues(!member.isUsePercentValuesEnabled());
                member.invalidate();
            }
        });

        member.animateY(1400, Easing.EaseInOutQuad);
        // chart.spin(2000, 0, 360);

        Legend l = member.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(0f);

        // entry label styling
        member.setEntryLabelColor(Color.WHITE);
        member.setEntryLabelTextSize(12f);
    }


    private void setClassifyData(List<InOutStatisticsBean.ClassifyMoneyBean> classifyMoneyBean) {
        ArrayList<PieEntry> entries = new ArrayList<>();
        if (classifyMoneyBean.size() == 0) {
            entries.add(new PieEntry(0, "无"));
        } else {
            for (int i = 0; i < classifyMoneyBean.size(); i++) {
                entries.add(new PieEntry((float) classifyMoneyBean.get(i).getMoney(),
                        classifyMoneyBean.get(i).getClassify()));
            }
        }

        PieDataSet dataSet = new PieDataSet(entries, "");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        // add a lot of colors
        dataSet.setColors(getDataColorList());
        //dataSet.setSelectionShift(0f);

        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.4f);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setValueLineColor(getResources().getColor(R.color.black50));

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter(classify));
        data.setValueTextSize(11f);
        data.setValueTextColor(getResources().getColor(R.color.black50));
        classify.setData(data);

        // undo all highlights
        classify.highlightValues(null);

        classify.invalidate();
    }

    private void setMemberData(List<InOutStatisticsBean.MemberMoneyBean> memberMoneyBean) {
        ArrayList<PieEntry> entries = new ArrayList<>();

        if (memberMoneyBean.size() == 0) {
            entries.add(new PieEntry(0, "无"));
        } else {
            for (int i = 0; i < memberMoneyBean.size(); i++) {
                entries.add(new PieEntry((float) memberMoneyBean.get(i).getMoney(),
                        memberMoneyBean.get(i).getMember()));
            }
        }


        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        // add a lot of colors
        dataSet.setColors(getDataColorList());
        //dataSet.setSelectionShift(0f);

        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.4f);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setValueLineColor(getResources().getColor(R.color.black50));

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter(member));
        data.setValueTextSize(11f);
        data.setValueTextColor(getResources().getColor(R.color.black50));
        member.setData(data);

        // undo all highlights
        member.highlightValues(null);

        member.invalidate();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mDialogYearMonth != null) {
            mDialogYearMonth.clearDialog();
            mDialogYearMonth = null;
        }
    }


    private ArrayList<Integer> getDataColorList() {
        ArrayList<Integer> colors = new ArrayList<>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.JOYFUL_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.COLORFUL_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.LIBERTY_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.PASTEL_COLORS) {
            colors.add(c);
        }

        colors.add(ColorTemplate.getHoloBlue());

        return colors;

    }


}
